<template>
  <section class="login-set-main">
    <el-tabs stretch class="set-inner" type="border-card">
      <el-tab-pane>
        <span slot="label">
          <i class="el-icon-setting" />设置管理员密码
        </span>
        <el-form ref="form" :model="form" :rules="rules" class="login-form set" auto-complete="on" label-position="left" label-width="80px">
          <section class="tag">
            <div>超级管理员手机号：{{ form.phoneNumber || '' }}</div>
            <div>(如果手机号不对或者有变更请联系平台管理员)</div>
          </section>
          <el-form-item prop="middle" label="手机号确认:">
            <el-input v-model.trim="form.middle" auto-complete="on" name="middle" maxlength="4" type="text" placeholder="请输入您手机号中以星号显示的4位数字" />
          </el-form-item>
          <el-form-item prop="msgCode" label="验证码:">
            <el-input v-model.trim="form.code" style="width: 50%" name="code" auto-complete="new-password" placeholder="请输入验证码" />
            <el-button type="text" :disabled="disabled=!show" class="sendcode" @click="handleSendCode">
              <span v-show="show">获取验证码</span>
              <span v-show="!show" class="count">{{ count }}s后重新获取</span>
            </el-button>
          </el-form-item>
          <el-form-item prop="password" label="密码:">
            <el-input v-model.trim="form.password" :type="pwdType" auto-complete="new-password" name="NewPassword" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item prop="confirmPassword" label="确认密码:">
            <el-input v-model.trim="form.confirmPassword" :type="pwdType" auto-complete="new-password" name="affirmPassword" placeholder="请输入确认密码" />
          </el-form-item>

          <el-button :loading="loading" type="primary" style="width:100%; height: 44px; margin-top: 20px;border-radius:20px;" @click.native.prevent="handleComit">确认</el-button>

          <el-button type="text" class="goback" @click="handleBack">返回登录</el-button>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </section>
</template>
<script>
import { getAdminPhoneCode, getPartOfAdminMobileNumber, resetAdminPassword } from '@/views/login/api/login'
export default {
  name: 'LoginSet',
  data() {
    return {
      loading: false,
      form: {
        phoneNumber: '',
        middle: '',
        code: '',
        password: '',
        confirmPassword: ''
      },
      rules: {
        middle: [{ trigger: 'blur', message: '请输入手机号码中间四位' }, {
          validator: (rule, value, callback) => {
            const reg = /^\+?[0-9][0-9]*$/
            if (!value) {
              callback(new Error('请输入手机号码中间四位'))
            } else if (!reg.test(value)) {
              callback(new Error('请输入正确的4位补齐号码！'))
            } else {
              callback()
            }
          }
        }],
        password: [{
          trigger: 'blur', validator: (rule, value, callback) => {
            const reg = /^(?!.*\s)(?!^[\u4e00-\u9fa5]+$)(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{8,30}$/
            if (!value) {
              callback(new Error('请输入新密码！'))
            } else if (!reg.test(value)) {
              callback(new Error('密码长度必须大于等于8位小于等于30位。必须包含大写字母、小写字母、数字、特殊字符中的3种。'))
            } else if (this.form.confirmPassword && value !== this.form.confirmPassword) {
              callback(new Error('两次输入密码不一致!'))
            } else {
              callback()
            }
          }
        }],
        confirmPassword: [{
          trigger: 'blur', validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请再次输入密码！'))
            } else if (value !== this.form.password) {
              callback(new Error('两次输入密码不一致!'))
            } else {
              callback()
            }
          }
        }],
        code: [{
          trigger: 'blur', validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入验证码！'))
            } else {
              callback()
            }
          }
        }]
      },
      phone: '',
      TIME_COUNT: 60,
      count: 0,
      show: true,
      pwdType: 'password',
      timer: null
    }
  },
  created() {
    this.getPhoneNumber()
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    sendCodeCheck() {
      const reg = /^1\d{10}$/
      if (this.form.middle === '') {
        this.$message({
          message: '请输入您手机号码中间四位！',
          type: 'warning'
        })
        return false
      } else {
        this.phone = this.form.phoneNumber.replace('****', this.form.middle)
        if (!reg.test(this.phone)) {
          this.$message({
            message: '请输入正确的4位补齐号码！',
            type: 'warning'
          })
          return false
        }
      }
      return true
    },

    check() {
      const reg = /^1\d{10}$/
      if (this.form.middle === '') {
        this.$message({
          message: '请输入您手机号码中间四位！',
          type: 'warning'
        })
        return false
      } else {
        this.phone = this.form.phoneNumber.replace('****', this.form.middle)
        if (!reg.test(this.phone)) {
          this.$message({
            message: '请输入正确的4位补齐号码！',
            type: 'warning'
          })
          return false
        }
      }
      if (!this.form.code) {
        this.$message({
          message: '请输入验证码！',
          type: 'warning'
        })
        return false
      }
      return true
    },

    handleSendCode() {
      if (this.sendCodeCheck()) {
        if (!this.timer) {
          this.count = this.TIME_COUNT
          this.show = false
          return new Promise((resolve, reject) => {
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= this.TIME_COUNT) {
                this.count--
              } else {
                this.show = true
                clearInterval(this.timer) // 清除定时器
                this.timer = null
              }
            }, 1000)
            getAdminPhoneCode({
              phoneNumber: this.form.phoneNumber.replace('****', this.form.middle),
              smsType: '0'
            }).then(res => {
              this.$message({
                message: '短信已发送，请注意查收！',
                type: 'success'
              })
            }).catch(error => {
              reject(error)
              this.show = true
              this.timer = null
            })
          })
        }
      }
    },

    handleBack() {
      this.$emit('closeset')
    },

    getPhoneNumber() {
      return new Promise((resolve, reject) => {
        getPartOfAdminMobileNumber().then((res) => {
          this.form.phoneNumber = res.data.data || ''
        }).catch(error => {
          reject(error)
        })
      })
    },

    handleComit() {
      if (this.check()) {
        this.$refs.form.validate(valid => {
          if (valid) {
            const formData = {
              phoneNumber: this.phone,
              smsCode: this.form.code,
              password: this.form.password,
              confirmPassword: this.form.confirmPassword
            }
            this.loading = true
            return new Promise((resolve, reject) => {
              resetAdminPassword(formData).then((res) => {
                this.loading = false
                this.$message({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 1000,
                  onClose: () => {
                    this.$alert(res.data.data, '提示', {
                      confirmButtonText: '确定',
                      callback: action => {
                        this.$emit('closeset')
                      }
                    })
                  }
                })
              }).catch(error => {
                this.loading = false
                reject(error)
              })
            })
          } else {
            return false
          }
        })
      }
    }
  }
}
</script>
<style lang="scss">
.login-set-main {
  width: 100%;
  height: 100%;
  position: relative;
  .set-inner {
    width: 460px;
    position: absolute;
    left: 0;
    right: 0;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    .tag {
      margin-bottom: 10px;
      font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
        Microsoft YaHei, SimSun, sans-serif;
      font-weight: 400;
      text-align: center;
      font-size: 14px;
      color: #409eff;
      background-color: #ecf5ff;
      padding: 0 10px;
      line-height: 25px;
      border: 1px solid #d9ecff;
      border-radius: 4px;
      box-sizing: border-box;
      white-space: nowrap;
      > div:last-child {
        color: red;
      }
    }
    .el-button.sendcode {
      border: none;
      position: absolute;
      right: 0;
      bottom: 12px;
      font-size: 12px;
      padding: 0;
    }
    .el-button.goback {
      width: 100%;
      margin-left: 0;
    }
  }
}
</style>
